import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    // 如果是 true 就是不需要鉴权
    meta: {
      auth: false
    },
    component: () => import('@/views/Login')
  },
  {
    path: '/home',
    name: 'home',
    // 如果是 true 就是需要鉴权
    meta: {
      auth: true
    },
    component: () => import('@/views/Home'),
    redirect: '/Welcome',
    children: [{
        // 欢迎页面
        path: '/Welcome',
        name: 'Welcome',
        component: () => import('@/views/Home/Welcome')
      },
      // 用户管理
      {
        path: '/users',
        name: 'Users',
        component: () => import('@/views/Home/Users')
      },
      // 权限管理
      {
        path: '/rights',
        name: 'Rights',
        component: () => import('../views/Home/Rights/Right.vue')
      },
      {
        path: '/roles',
        name: 'Roles',
        component: () => import('../views/Home/Rights/Roles.vue')
      },
      // 权限管理
      {
        // 商品 列表
        path: '/goods',
        name: 'goods',
        component: () => import('../views/Home/Goods/GoodList.vue')
      },
      {
        // 商品 添加
        path: '/goodsAdd',
        name: 'GoodsAdd',
        component: () => import('../views/Home/Goods/GoodsAdd.vue')
      },
      // 
      {
        // 商品 参数
        path: '/params',
        name: 'params',
        component: () => import('../views/Home/Goods/GoodsCate.vue')
      },
      {
        // 商品 编辑
        path: '/goodEdit',
        name: 'goodEdit',
        component: () => import('../views/Home/Goods/GoodEdit.vue')
      },
      {
        // 商品 分类
        path: '/categories',
        name: 'categories',
        component: () => import('../views/Home/Goods/GoodFenLei.vue')
      },
      {
        //订单管理
        path: '/orders',
        name: 'orders',
        component: () => import('@/views/Home/Orders')
        // component: () => import('../views/Home/Orders/index.vue')
      },
      {
        // 数据报表
        path: '/reports',
        name: 'reports',
        component: () => import('@/views/Home/Reports')
      },
    ]
  }
]

const router = new VueRouter({
  routes
})


// 路由拦截     去哪里，从哪来，下一步（放行）
router.beforeEach((to, from, next) => {
  const flag = to.matched.some(item => { // some 有一个是true 他就返回true
    return item.meta.auth
  })
  // 判断页面是否需要鉴权鉴权 
  if (flag) {
    // 如果需要鉴权， 则获取本地没有token
    const token = sessionStorage.getItem('token')
    if (!token) {
      // router.push('/login')
      return next({
        path: '/login'
      })
    }

    next()
  } else {
    next()
  }
})

export default router
